Ext.define('YXMES.smat.controller.MaterialLabelPrintController', {
	extend : 'Ext.app.Controller',
	refs : [ {
		selector : 'smat_materiallabelprint',
		ref : 'smatmateriallabelprint'
	} ],
	requires : [ 'YXMES.smat.store.SupplierStore', 'YXMES.smat.store.MaterialStore', 'YXMES.smat.store.ReceiveMatLabelStore', 'YXMES.smat.store.WarehouseStore' ],
	stores : [],
	models : [],
	views : [ 'YXMES.smat.view.MaterialLabelPrintView' ],
	subcontrollers : [  ],
	_init : false,
	init : function() {
		if (this._init)
			return;
		this._init = true;
		this.control({
			'smat_materiallabelprint' : {
				afterrender : function() {
					return this.handle(this.onAfterrender, arguments);
				},
				destroy : function() {
					return this.handle(this.onDestroy, arguments);
				}
			},
			'smat_materiallabelprint #btnSearch' : {
				click : function() {
					return this.handle(this.onBtnSearchClick, arguments);
				}
			},
			'smat_materiallabelprint #btnClear' : {
				click : function() {
					return this.handle(this.onBtnClearClick, arguments);
				}
			},
			'smat_materiallabelprint #btnPrint' : {
				click : function() {
					return this.handle(this.onBtnPrintClick, arguments);
				}
			},
			'smat_materiallabelprint #btnPrintList' : {
				click : function() {
					return this.handle(this.onBtnPrintListClick, arguments);
				}
			},
			'smat_materiallabelprint #btnReset' : {
				click : function() {
					return this.handle(this.onBtnResetClick, arguments);
				}
			}
		});
		if (!Ext.isEmpty(this.subcontrollers)) {
			Ext.each(this.subcontrollers, function(name) {
				this.getController(name).init();
			}, this);
		}
		// User definied init
	},
	mainView : undefined,
	getMainView : function() {
		return this.mainView;
	},
	getScopeView : function() {
		return this.getMainView().scopeView || {};
	},
	getInput : function() {
		return this.getScopeView().input || {};
	},
	setInput : function(data) {
		this.getMainView().input = data;
	},
	getOutput : function() {
		return this.getMainView().output || {};
	},
	setOutput : function(data) {
		this.getScopeView().output = data;
	},
	handle : function(func, args) {
		var item = args && args.length > 0 && Ext.typeOf(args[0]) === 'object' ? args[0] : undefined;
		if (item) {
			try {
				this.mainView = (item.xtype == 'smat_materiallabelprint' ? item : item.up('smat_materiallabelprint'));
			} catch(e) {
			}
		}
		try {
			return func.apply(this, args);
		} finally {
		}
	},
	getItem : function(itemId) {
		return itemId===this.getMainView().getItemId()?this.getMainView():this.getMainView().down('#' + itemId);
	},
	getStore : function(name) {
		if (name == 'SupplierStore')
			return this.getMainView().SbasViewSupplierRosterServiceStore;
		if (name == 'MaterialStore')
			return this.getMainView().SbasViewBaseMaterialServiceStore;
		if (name == 'ReceiveMatLabelStore')
			return this.getMainView().SmatViewPrintedMaterialSnServiceStore;
		if (name == 'WarehouseStore')
			return this.getMainView().SbasViewWarehouseDefinitionServiceStore;
		return undefined;
	},
	bind : function(view) {
		view = (view ? view : this.getMainView());
		view.SbasViewSupplierRosterServiceStore = Ext.create('YXMES.smat.store.SupplierStore', {
			pageSize : 30,
			autoDestory : true,
			autoLoad : true
		});
		view.SbasViewBaseMaterialServiceStore = Ext.create('YXMES.smat.store.MaterialStore', {
			pageSize : 30,
			autoDestory : true,
			autoLoad : true
		});
		view.SmatViewPrintedMaterialSnServiceStore = Ext.create('YXMES.smat.store.ReceiveMatLabelStore', {
			pageSize : 30
		});
		view.SbasViewWarehouseDefinitionServiceStore = Ext.create('YXMES.smat.store.WarehouseStore', {
			pageSize : 30,
			autoDestory : true,
			autoLoad : true
		});
		view.down('#cdvSupCode').bindStore(view.SbasViewSupplierRosterServiceStore);
		view.down('#cdvMatCode').bindStore(view.SbasViewBaseMaterialServiceStore);
		view.down('#grdList').reconfigure(view.SmatViewPrintedMaterialSnServiceStore);
		view.down('#bar30').bindStore(view.SmatViewPrintedMaterialSnServiceStore);
		view.down('#cmbWhCode').bindStore(view.SbasViewWarehouseDefinitionServiceStore);
	},
	onAfterrender : function(container, eOpts) {
		this.bind();
		// User defined afterrender
		var dtFrom = new Date();
		var dtTo = new Date();
		dtFrom.setDate(dtFrom.getDate() - 1);
		dtTo.setDate(dtTo.getDate() + 1);
		this.getItem('dteSearchFrom').setValue(dtFrom.startDay());
		this.getItem('dteSearchEnd').setValue(dtTo.endDay());
		
		this.showMsg('请录入来料信息，然后点击打印生成标签。');
	},
	onDestroy : function(container, eOpts) {
		// User defined destory
		var view = this.getMainView();
		if (view.SbasViewSupplierRosterServiceStore) {
			view.SbasViewSupplierRosterServiceStore.destroyStore();
			view.SbasViewSupplierRosterServiceStore = undefined;
		}
		if (view.SbasViewBaseMaterialServiceStore) {
			view.SbasViewBaseMaterialServiceStore.destroyStore();
			view.SbasViewBaseMaterialServiceStore = undefined;
		}
		if (view.SmatViewPrintedMaterialSnServiceStore) {
			view.SmatViewPrintedMaterialSnServiceStore.destroyStore();
			view.SmatViewPrintedMaterialSnServiceStore = undefined;
		}
		if (view.SbasViewWarehouseDefinitionServiceStore) {
			view.SbasViewWarehouseDefinitionServiceStore.destroyStore();
			view.SbasViewWarehouseDefinitionServiceStore = undefined;
		}
		if (this.getMainView().input)
			this.getMainView().input = undefined;
		if (this.getMainView().output)
			this.getMainView().output = undefined;
	},
	onBtnSearchClick : function(button, e, eOpts) {
		this.loadReceiveMatLabelStore({
		    supCode: this.getItem('cdvSearchSupCode').getValue(),
		    matCode: this.getItem('cdvSearchMatCode').getValue(),
		    deliveryNo: this.getItem('txtSearchDeliveryNo').getValue(),
		    fromDate: this.getItem('dteSearchFrom').getValue(),
		    toDate: this.getItem('dteSearchEnd').getValue()
		});
	},
	onBtnClearClick : function(button, e, eOpts) {
		this.getItem('cdvSearchSupCode').setValue('');
		this.getItem('cdvSearchMatCode').setValue('');
		this.getItem('txtSearchDeliveryNo').setValue('');
		this.getItem('dteSearchFrom').setValue(new Date()-1);
		this.getItem('dteSearchEnd').setValue(new Date());
	},
	onBtnPrintClick : function(button, e, eOpts) {
		this.showMsg('正在保存并生成标签，首次打印会较慢，请耐心等待...');
		
		if (!this.getItem('frmLabel').isValid()) {
		    this.showMsg('数据不完整，请查检。');
		    return;
		}
		
		var me = this;
		var vals = me.getItem('frmLabel').getValues();
		if (parseFloat(vals.labelQty) > parseFloat(vals.deliveryQty)) {
		    this.showMsg('最小包装数量不能超过送货数。',true);
		    return;
		}
		
		var mainForm = me.getItem('frmMain');
		var dtFrom = new Date();
		var dtTo = new Date();
		//dtFrom.setDate(dtFrom.getDate() - 1);
		//dtTo.setDate(dtTo.getDate() + 1);
		Ext.Msg.show({
		    title: T.label.save,
		    msg: T.msg.are_you_sure_to_save_data,
		    icon: Ext.Msg.QUESTION,
		    buttons: Ext.Msg.YESNO,
		    fn: function(btnId) {
		        if ('yes' == btnId) {
		            button.setDisabled(true);
		
		            YX.ZbusRpc.request({
		                module: 'SmatSaveReceiveMaterialAndPrintService',
		                showSuccess: false,
		                params: vals,
		                failure: function(rsp) {
		                    me.showMsg('操作失败:' + rsp.rspDesc + "。",true);
		                },
		                success: function(rsp) {
		                    me.showMsg('操作成功。');
		
		                    me.getItem('frmLabel').getForm().setValues({
		                        supCode: vals.supCode,
		                        supName: vals.supName,
		                        matCode: vals.matCode,
		                        matDesc: vals.matDesc
		                    });
		                    me.loadReceiveMatLabelStore({
		                        supCode: vals.supCode,
		                        matCode: vals.matCode,
		                        deliveryNo: vals.deliveryNo,
		                        fromDate: dtFrom.startDay(),
		                        toDate: dtTo.endDay()
		                    });
		
		                    if (!Ext.isEmpty(rsp.fileName)) {
		                        Ext.create('Ext.window.Window', {
		                            title: '标签打印',
		                            height: mainForm.getHeight() - 50,
		                            width: mainForm.getWidth() - 200,
		                            layout: 'fit',
		                            modal: true,
		                            frame: false,
		                            items: [{
		                                html: '<iframe style="width:100%;height:100%" src="export?download=0&fileName=' + rsp.fileName + '"/>'
		                            }]
		                        }).show();
		                    }
		                },
		                callback: function() {
		                    button.setDisabled(false);
		                }
		            });
		        }
		    }
		});
	},
	onBtnPrintListClick : function(button, e, eOpts) {
		var rcds = this.getItem('grdList').getSelectionModel().getSelection();
		if (Ext.isEmpty(rcds)) {
		    return;
		}
		
		var me = this;
		var myMask = new Ext.LoadMask(me.getItem('pnlInfo'), {
		    msg: "首次打印会较慢，请耐心等待..."
		});
		myMask.show();
		
		var vMsns = "";
		Ext.each(rcds,
		function(rcd) {
		    vMsns += rcd.get('msn') + ",";
		});
		
		var mainForm = me.getItem('frmMain');
		button.setDisabled(true);
		
		YX.ZbusRpc.request({
		    module: 'SmatViewMaterialSnToPrintLabelService',
		    showSuccess: false,
		    params: {
		        msns: vMsns
		    },
		    success: function(rsp) {
		        if (!Ext.isEmpty(rsp.fileName)) {
		            Ext.create('Ext.window.Window', {
		                title: '标签打印',
		                height: mainForm.getHeight() - 50,
		                width: mainForm.getWidth() - 200,
		                layout: 'fit',
		                modal: true,
		                frame: false,
		                items: [{
		                    html: '<iframe style="width:100%;height:100%" src="export?download=0&fileName=' + rsp.fileName + '"/>'
		                }]
		            }).show();
		        }
		    },
		    callback: function() {
		        button.setDisabled(false);
		        myMask.hide();
		    }
		});
	},
	onBtnResetClick : function(button, e, eOpts) {
		this.getItem('frmLabel').getForm().reset();
	},
	loadSupplierStore : function(params, options) {
		params = Ext.applyIf(params||{}, {
			// Default params
		});
		
		var store = this.getStore('SupplierStore');
		if(!store) {
			return false;
		}
		
		store.getProxy().extraParams = params;
		if(store.loadPage){
			store.loadPage(1, options);
		}else{
			store.load(options);
		}
	},
	loadMaterialStore : function(params, options) {
		params = Ext.applyIf(params||{}, {
			// Default params
		});
		
		var store = this.getStore('MaterialStore');
		if(!store) {
			return false;
		}
		
		store.getProxy().extraParams = params;
		if(store.loadPage){
			store.loadPage(1, options);
		}else{
			store.load(options);
		}
	},
	loadReceiveMatLabelStore : function(params, options) {
		params = Ext.applyIf(params||{}, {
			// Default params
		});
		
		var store = this.getStore('ReceiveMatLabelStore');
		if(!store) {
			return false;
		}
		
		store.getProxy().extraParams = params;
		if(store.loadPage){
			store.loadPage(1, options);
		}else{
			store.load(options);
		}
	},
	loadWarehouseStore : function(params, options) {
		params = Ext.applyIf(params||{}, {
			// Default params
		});
		
		var store = this.getStore('WarehouseStore');
		if(!store) {
			return false;
		}
		
		store.getProxy().extraParams = params;
		if(store.loadPage){
			store.loadPage(1, options);
		}else{
			store.load(options);
		}
	},
	showMsg : function(msg, isError) {
		var infoPanel = this.getItem('pnlInfo');
		
		if (Ext.isEmpty(msg)) {
		    infoPanel.update();
		    return;
		}
		
		var data = {
		    info: (isError ? "": msg),
		    errInfo: (isError ? msg: "")
		};
		
		infoPanel.update(data);
	}
});